package com.lagou.v4.container;

import com.lagou.v4.LifeCycle;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/02
 */
public class Context implements LifeCycle {
    /**
     * appBase目录下的直接子目录文件夹名
     */
    private String contextPath;
    /**
     * 当前web应用对应web.xml的路径
     */
    private File xmlFile;

    private List<Wrapper> wrappers;

    public File getXmlFile() {
        return xmlFile;
    }

    public void setXmlFile(File xmlFile) {
        this.xmlFile = xmlFile;
    }

    public List<Wrapper> getWrappers() {
        return wrappers;
    }

    public void setWrappers(List<Wrapper> wrappers) {
        this.wrappers = wrappers;
    }

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    @Override
    public void init() throws Exception {
        initWrapper();
    }

    private void initWrapper() throws Exception {
        File parent = xmlFile.getParentFile();
        URL url = parent.listFiles()[0].toURI().toURL();
        URLClassLoader classLoader = new URLClassLoader(new URL[]{url}, ClassLoader.getSystemClassLoader());

        Document document = new SAXReader().read(xmlFile);
        Element rootElement = document.getRootElement();
        List<Element> servletElements = rootElement.elements("servlet");
        List<Element> mappings = rootElement.elements("servlet-mapping");
        wrappers = new ArrayList<>(servletElements.size());
        for (Element servletElement : servletElements) {
            Element nameElement = servletElement.element("servlet-name");
            Element classElement = servletElement.element("servlet-class");

            Element anElse = mappings.stream().filter(element ->
                    element.element("servlet-name").getStringValue().equals(nameElement.getStringValue()))
                    .findFirst().orElse(null);
            Element urlElement = anElse.element("url-pattern");

            Wrapper wrapper = new Wrapper();
            wrapper.setServletName(nameElement.getStringValue());
            wrapper.setServletClass(classElement.getStringValue());
            wrapper.setUrlPattern(urlElement.getStringValue());
            wrapper.setClassLoader(classLoader);
            wrappers.add(wrapper);
            wrapper.init();
        }

    }

    @Override
    public void start() throws Exception {

    }
}
